package algo.ch0105;

/**
 * @author mougua
 */
public class UfQuickFind {
    private final int[] id;
    private int count;
    
    public UfQuickFind(int n) {
        count = n;
        id = new int[n];
        for (int i = 0; i < n; i++) {
            // 右边的i表示第i个连通分量
            id[i] = i;
        }
    }

    public void union(int p, int q) {
        int pid = find(p);
        int qid = find(q);

        if (pid == qid) {
            return;
        }
        for (int i = 0; i < id.length; i++) {
            if (id[i] == pid) {
                id[i] = qid;
            }
        }
        count--;
    }

    public int find(int p) {
        return id[p];
    }

    public boolean connected(int p, int q) {
        return find(p) == find(q);
    }

    public int count() {
        return count;
    }
}
